package com.youi.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youi.shop.commons.exceptions.GlobalException;
import com.youi.shop.commons.result.RespEntity;
import com.youi.shop.commons.result.StatusCode;
import com.youi.shop.mapper.UserMapper;
import com.youi.shop.pojo.entity.User;
import com.youi.shop.pojo.qo.user.UserLoginParams;
import com.youi.shop.pojo.qo.user.UserRegisterParams;
import com.youi.shop.pojo.vo.user.UserVO;
import com.youi.shop.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 商家表 服务实现类
 * </p>
 *
 * @author xxf
 * @since 2020-11-09
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    UserMapper userMapper;

    /**
     * 通过用户名查询member对象校验密码
     *
     * @param params
     * @return
     */
    @Override
    public RespEntity<UserVO> selectOne(UserLoginParams params) {
        //条件构造
//        QueryWrapper<User> wrapper = new QueryWrapper<>();
//        wrapper.eq("username", params.getUsername());
        //查询返回结果
//        User user = userMapper.selectOne(wrapper);
        User user = userMapper.selectByUsername(params.getUsername());

        RespEntity<UserVO> respEntity = null;

        if (user == null) {
            //该用户名未注册，返回错误消息
            throw new GlobalException(StatusCode.USERNAME_UNMATCHED_ERROR);
        } else {

            //校验密码
            if (params.getPassword().equals(user.getPassword())) {
                UserVO userVO = new UserVO();
                BeanUtils.copyProperties(user, userVO);
                respEntity = RespEntity.success(userVO);
            } else {
                //密码错误
                respEntity = RespEntity.error(StatusCode.LOGIN_ERROR);
            }

        }
        return respEntity;
    }

    /**
     * 添加一个商家
     *
     * @param params
     * @return
     */
    @Override
    public boolean insert(UserRegisterParams params) {

        //查询数据库

        //返回查询结果
        User user = userMapper.selectByUsername(params.getUsername());

        boolean flag = false;

        if (user != null && user.getUsername().equals(params.getUsername())) {
            //用户已存在
            throw new GlobalException(StatusCode.REGISTER_ERROR);
        } else {
            //将会员注册信息存入数据库
            user = new User();
            BeanUtils.copyProperties(params, user);
            //保存成功 返回true
            int res = userMapper.insert(user);
            if (res > 0) {
                flag = true;
            }
        }


        return flag;

    }
}
